package com.ajie.bluetoothcard.ui;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import com.ajie.bluetoothcard.db.DBApi;
import com.ajie.bluetoothcard.domain.Card;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;
public class EditCardInfoActivity extends BaseActivity implements OnCheckedChangeListener{
	private Button change_pic,save;
	private EditText name,mobilePhone,telephone,title,company,address,url,email,fax;
	private String avatar_value = "",voide_value = "",name_value,mobilePhone_value,telephone_value,title_value,company_value,address_value,url_value,email_value,fax_value;
//	private CircularImage cover_user_photo;
	TextView card_time,card_sex,card_type;
	private Card card;
	private String type = "edit";
	private Bitmap avatatBitmap ;
	private Button record_start,record_stop;
//	private int mHeight;
	private MediaRecorder mediaRecorder;
	private long recordStartTime, recordEndTime;
	private String recordDirPath,recordFilePath,recordFileName;
	private boolean isRecord = false;
	private boolean isPlaying = false;
	private View voide_layout;
	private ToggleButton voideButton;
	private boolean addMe = false;//是不是要增加自己
	private ImageView avatar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.edit_my_card);
		super.onCreate(savedInstanceState);
		card = (Card) getIntent().getSerializableExtra("card");
		type = getIntent().getStringExtra("type");
		addMe = getIntent().getBooleanExtra("addMe", false);
		initView();
		initData();
	}
	private void initData() {
		if(card!=null){
			avatar_value = card.getAvatar();
			voide_value = card.getVoide();
			name.setText(card.getName());	
			mobilePhone.setText(card.getMobilePhone());	
			telephone.setText(card.getTelephone());	
			title.setText(card.getTitle());	
			company.setText(card.getCompany());	
			address.setText(card.getAddress());	
			url.setText(card.getUrl());	
			email.setText(card.getEmail());	
			fax.setText(card.getFax());	
			if(!"".equals(avatar_value)){
				avatatBitmap = BitmapFactory.decodeFile(avatar_value);
				if(avatatBitmap!=null){
					avatar.setImageBitmap(avatatBitmap );
				}else{
					showToast("头像丢失");
				}
			}
			
			if(!"".equals(voide_value)){
				voide_layout.setVisibility(View.VISIBLE);
			}
		}else{
			card = new Card();
		}
//		if(card!=null){
//			card_avatar_value = card.getAvatar();
//			card_voide_value = card.getVoide();
//			card_name_value = card.getName();
//			card_phone_value = card.getPhone();
//			card_age_value = card.getAge();
//			card_address_value = card.getAddress();
//			card_introduction_value = card.getIntroduction();
//			card_sex_value = card.getSex();
//			card_type_value = card.getType();
//			
//			card_name.setText(card.getName());	
//			card_phone.setText(card.getPhone());	
//			card_age.setText(card.getAge());	
//			card_address.setText(card.getAddress());	
//			card_time.setText(card.getTime());	
//			card_introduction.setText(card.getIntroduction());
//			if("1".equals(card.getSex())){
//				card_sex.setText(getString(R.string.man));
//			}else{
//				card_sex.setText(getString(R.string.woman));
//			}
//			if("1".equals(card.getType())){
//				card_type.setText(R.string.rich);	
//			}else{
//				card_type.setText(R.string.poor);	
//			}
//			if(!"".equals(card_avatar_value)){
//				avatatBitmap = BitmapFactory.decodeFile(card_avatar_value);
//				if(avatatBitmap!=null){
//					cover_user_photo.setImageBitmap(avatatBitmap );
//				}else{
//					showToast("头像丢失");
//				}
//			}
////			if(!"".equals(card_voide_value)){
////				video_layout.setVisibility(View.VISIBLE);
////			}else{
////				video_layout.setVisibility(View.GONE);
////			}
//		}else{
//			card = new Card();
//		}
	}
	@Override
	protected void initView() {
		super.initView();
		
		name = (EditText) findViewById(R.id.name);
		mobilePhone = (EditText) findViewById(R.id.mobilePhone);
		telephone = (EditText) findViewById(R.id.telephone);
		title = (EditText) findViewById(R.id.title);
		company = (EditText) findViewById(R.id.company);
		address = (EditText) findViewById(R.id.address);
		url = (EditText) findViewById(R.id.url);
		email = (EditText) findViewById(R.id.email);
		fax = (EditText) findViewById(R.id.fax);
		
		avatar = (ImageView) findViewById(R.id.avatar);
		voide_layout =  findViewById(R.id.voide_layout);
		
		change_pic = (Button) findViewById(R.id.change_pic);
		change_pic.setOnClickListener(this);
		record_start = (Button) findViewById(R.id.record_start);
		record_start.setOnClickListener(this);
		record_stop = (Button) findViewById(R.id.record_stop);
		record_stop.setOnClickListener(this);
		save = (Button) findViewById(R.id.save);
		save.setOnClickListener(this);
		
		
		
		
//		btn_next.setVisibility(View.VISIBLE);
//		top_title_right.setText("保存");
//		cover_user_photo = (CircularImage) findViewById(R.id.cover_user_photo);
//		cover_user_photo.setImageResource(R.drawable.avatar_profile);
//		cover_user_photo.setOnClickListener(this);
//
		voideButton = (ToggleButton) findViewById(R.id.voideButton);
		voideButton.setOnCheckedChangeListener(this);
//		card_sex = (TextView) findViewById(R.id.card_sex);
//		card_sex.setOnClickListener(this);
//		card_type = (TextView) findViewById(R.id.card_type);
//		card_type.setOnClickListener(this);
//		card_name = (EditText) findViewById(R.id.card_name);
//		card_phone = (EditText) findViewById(R.id.card_phone);
//		card_age = (EditText) findViewById(R.id.card_age);
//		card_address = (EditText) findViewById(R.id.card_address);
//		card_time = (TextView) findViewById(R.id.card_time);
//		card_introduction = (EditText) findViewById(R.id.card_introduction);
//		video_layout =  findViewById(R.id.video_layout);
//		
//		record_start = (Button) findViewById(R.id.record_start);
//		record_start.setOnClickListener(this);
//		record_stop = (Button) findViewById(R.id.record_stop);
//		record_stop.setOnClickListener(this);
//		voiceCancelText = (TextView) findViewById(R.id.voice_cancel_hint);
//		voiceCancelImage = (ImageView) findViewById(R.id.voice_cancel_img);
//		voiceCancelAnim = AnimationUtils.loadAnimation(this, R.anim.voice_cancel_scale);

	}
	
	private void evaluation() {
		
		
		name_value = name.getText().toString();
		mobilePhone_value = mobilePhone.getText().toString();
		telephone_value = telephone.getText().toString();
		title_value = title.getText().toString();
		company_value = company.getText().toString();
		address_value = address.getText().toString();
		url_value = url.getText().toString();
		email_value = email.getText().toString();
		fax_value = fax.getText().toString();
		
		
		card.setName(name_value);
		card.setMobilePhone(mobilePhone_value);
		card.setTelephone(telephone_value);
		card.setTitle(title_value);
		card.setCompany(company_value);
		card.setAddress(address_value);
		card.setUrl(url_value);
		card.setEmail(email_value);
		card.setFax(fax_value);
		if("".equals(name_value)||"".equals(mobilePhone_value)){
			showToast("姓名和手机号码不能为空");
		}else{
			File file = new File(card.getVoide());
			if(file.exists()){
				file.delete();
			}
			card.setAvatar(avatar_value);
			card.setVoide(voide_value);
			dispose();
		}
	}
	
	private void dispose() {
		if("add".equals(type)){
			if(addMe){
				card.setType("0");
				card.setIsDel("2");
			}else{
				card.setIsDel("0");
			}
			showToast("插入成功");
			DBApi.getInstance(this).insertCard(card);
		}else{
			showToast("修改成功");
			DBApi.getInstance(this).updateRecord(card);
		}
		Intent intent = new Intent();
		intent.putExtra("card", card);
		this.setResult(20001, intent);
		this.finish();
	}
	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
//		case R.id.change_voide:
//			evaluation();
//			break;
		case R.id.change_pic:
			imageDialog(this, imageListener);
			break;
		case R.id.save:
			if(isRecord){
				showToast("正在录音中...");
			}else{
				evaluation();
			}
			break;
		case R.id.btn_next:
			evaluation();
			break;
		case R.id.cover_user_photo:
			imageDialog(this, imageListener);
			break;
		case R.id.record_start:
			startRecord();
			break;
		case R.id.record_stop:
			overRecord();
			break;

		default:
			break;
		}
	}
	
	protected void showDialog() {
		new AlertDialog.Builder(this).setTitle("确定替换？")
		.setMessage("您确定要替换现有的语音吗？")
		.setPositiveButton("确定", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				voide_value = recordFilePath;
				voide_layout.setVisibility(View.VISIBLE);
			}
		}).setNegativeButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				
			}
		}).create().show();
	}
	
	
	protected Intent intent = null;
	protected android.content.DialogInterface.OnClickListener imageListener = new android.content.DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case 0:
				intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
						Environment.getExternalStorageDirectory(), "temp.jpg")));
				startActivityForResult(intent, PHOTOHRAPH);
			break;
			case 1:
				intent = new Intent(Intent.ACTION_GET_CONTENT, null);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						IMAGE_UNSPECIFIED);
				startActivityForResult(intent, PHOTOZOOM);
			break;
			}
		}
	};
	protected void imageDialog(Context context, android.content.DialogInterface.OnClickListener dialogListener) {
		new AlertDialog.Builder(context).setTitle("请选择图片上传方式")
				.setItems(R.array.image_selector, dialogListener).show();
	}
	
	
	
	protected static final int NONE = 0;
	protected static final int PHOTOHRAPH = 1;// 拍照
	protected static final int PHOTOZOOM = 2; // 缩放
	protected static final int PHOTORESOULT = 3;// 结果
	
	protected static final String IMAGE_UNSPECIFIED = "image/*";
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == NONE)
			return;
		// 拍照
		if (requestCode == PHOTOHRAPH) {
			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			System.out.println("------------------------" + picture.getPath());
			startPhotoZoom(Uri.fromFile(picture));
		}

		if (data == null)
			return;

		// 读取相册缩放图片
		if (requestCode == PHOTOZOOM) {
			startPhotoZoom(data.getData());
		}
		// 处理结果
		if (requestCode == PHOTORESOULT) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap photo = extras.getParcelable("data");
				saveBitmap(photo);
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -
																		// 100)压缩文件
//				uploadImageView.setImageBitmap(photo);
				avatar.setImageBitmap(photo);
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveBitmap(Bitmap bm) { 
//		File f = new File(/*"/sdcard/"*/Environment.getExternalStorageDirectory().getPath(), "image.png"); 
		String path = UUID.randomUUID().toString().hashCode()+".png";
		File f = new File(CardApplication.getRootDir(), path); 
		avatar_value = CardApplication.getRootDir()+"/"+path;
		if (f.exists()) { 
			f.delete(); 
		} 
		try { 
		FileOutputStream out = new FileOutputStream(f); 
		bm.compress(Bitmap.CompressFormat.PNG, 90, out); 
		out.flush(); 
		out.close(); 
		} catch (FileNotFoundException e) { 
		e.printStackTrace(); 
		} catch (IOException e) { 
		e.printStackTrace(); 
		} 
		} 
	 
	protected void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", avatar.getWidth());
		intent.putExtra("outputY", avatar.getHeight());
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PHOTORESOULT);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(avatatBitmap!=null){
			avatatBitmap.recycle();
		}
		stopRecord();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		stopRecord();
	}
	
	private void overRecord() {
		stopRecord();
		long recordMillis = recordEndTime - recordStartTime;
		if(recordMillis<1000){
			showToast("录音时间太短！");
			return;
		}
		if(!"".equals(voide_value)){
			showDialog();
		}else{
			voide_value = recordFilePath;
			voide_layout.setVisibility(View.VISIBLE);
		}
	}
	protected void startRecord(){
		if(isRecord||isPlaying){
			if(isPlaying){
				showToast("正在播放音频中。。。");
			}else{
				showToast("正在录音中。。。");
			}
		}else{
			isRecord = true;
			record_stop.setVisibility(View.VISIBLE);
			record_start.setText("正在录音中。。。");
			recordStartTime = System.currentTimeMillis();
			mediaRecorder = new MediaRecorder();
			mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
			mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
			mediaRecorder.setAudioEncoder(3);
			recordDirPath = CardApplication.getRootDir()+ "/";
			recordFileName = UUID.randomUUID().toString();
			recordFilePath = recordDirPath+recordFileName.hashCode()+".amr";
			mediaRecorder.setOutputFile(recordFilePath);
			try {
				mediaRecorder.prepare();
				mediaRecorder.start();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	protected void stopRecord(){
		stopAudio(mMediaPlayer);
		isRecord = false;
		record_stop.setVisibility(View.GONE);
		record_start.setText("按住录音");
		recordEndTime = System.currentTimeMillis();
		if (this.mediaRecorder != null) {
			try{
	            this.mediaRecorder.stop();
			}catch(Exception e){
				e.printStackTrace();
			}
            this.mediaRecorder.release();
            this.mediaRecorder = null;
        }
	}

	MediaPlayer mMediaPlayer = null;
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(buttonView.getId() == R.id.voideButton){
			if(isChecked){
//				if(mMediaPlayer!=null){
//					mMediaPlayer.setOnCompletionListener(null);
//				}
				if(isRecord){
					showToast("您正在录音中。。。");
					voideButton.setChecked(false);
					return;
				}
//				stopAudio(mMediaPlayer);
//				File file = new File(CardApplication.getAudioRootDir(),card.getVoide());
				File file = new File(voide_value);
				isPlaying = true;
				if(file.exists()){
					Uri uri = Uri.fromFile(file);
					mMediaPlayer = MediaPlayer.create(this, uri);
					if(mMediaPlayer!=null){
						mMediaPlayer.start();
						mMediaPlayer.setOnCompletionListener(new CompletionListener());
					}else{
						showToast("音频有问题，请重新录制");
					}
				}else{
					voideButton.setChecked(false);
					showToast("音频丢失");
				}
			}else{
				isPlaying = false;
				stopAudio(mMediaPlayer);
			}
		}
	}
	
	public void stopAudio(MediaPlayer mp) {
		try {
			if(mp!=null){
				mp.stop();
				mp.release();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	class CompletionListener implements OnCompletionListener {
		@Override
		public void onCompletion(MediaPlayer mp) {
			isPlaying = false;
			voideButton.setChecked(false);
			stopAudio(mp);
		}
	}
}